package com.sunday.aomi.ui.common;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.statusbar.StatusBarUtil;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.ViewPager;
import com.sunday.aomi.R;
import com.sunday.aomi.base.BaseApp;
import com.sunday.aomi.entity.PushResult;
import com.sunday.aomi.http.ApiClient;
import com.sunday.aomi.push.PushIntentService;
import com.sunday.aomi.push.PushService;
import com.sunday.aomi.ui.login.ShopLoginActivity;
import com.sunday.aomi.ui.main.CartFragment;
import com.sunday.aomi.ui.main.IndexFragment;
import com.sunday.aomi.ui.main.MineExtraFragment;
import com.sunday.aomi.ui.main.MineFragment;
import com.sunday.aomi.ui.main.TransferFragment;
import com.sunday.member.SessionToken;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.Member;
import com.sunday.member.entity.Version;
import com.sunday.member.http.MemberClient;
import com.sunday.member.update.UpdateDialogActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;


public class MainActivity extends BaseActivity {

    @Bind(R.id.tab1)
    TextView tab1;
    @Bind(R.id.tab2)
    TextView tab2;
    @Bind(R.id.tab3)
    TextView tab3;
    @Bind(R.id.tab4)
    TextView tab4;

    @Bind(R.id.content)
    ViewPager viewPager;

    private ArrayList<Fragment> fragments;
    private Member member;
    private int pageNo = 0;
    private int userType;
    private ArrayList<TextView> tabViews = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        tabViews.add(tab1);
        tabViews.add(tab2);
        tabViews.add(tab3);
        tabViews.add(tab4);
        member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
        if (member != null) {
            BaseApp.getInstance().setMember(member);
            userType = member.getUserType();
            SessionToken.accountId = String.valueOf(member.getId());
            SessionToken.token = member.getToken();
        } else {
            boolean isFirst = SharePerferenceUtils.getIns(mContext).getBoolean(ConstValue.IS_FIRST, true);
            if (isFirst) {
                intent = new Intent(mContext, GuideActivity.class);
                startActivity(intent);
            } else {
                intent = new Intent(mContext, ShopLoginActivity.class);
                startActivity(intent);
            }
            finish();
        }
        fragments = new ArrayList<>(userType == 3 ? 3 : 4);
        fragments.add(IndexFragment.newInstance());
        fragments.add(CartFragment.newInstance(false));
        if (userType == 2) {
            fragments.add(TransferFragment.newInstance());
        } else if (userType == 3) {
            tabViews.get(2).setVisibility(View.GONE);
            tabViews.remove(2);
        }
       /* tabViews.get(2).setVisibility(View.GONE);
        tabViews.remove(2);*/
        fragments.add(userType == 2 ? MineFragment.newInstance() : MineExtraFragment.newInstance());
        tabViews.get(pageNo).setSelected(true);
        viewPager.setCurrentItem(pageNo, false);
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(userType == 3 ? 3 : 4);
        //viewPager.setOffscreenPageLimit(3);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < tabViews.size(); i++) {
                    tabViews.get(i).setSelected(false);
                }
                tabViews.get(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        checkAppPermission();
        checkUpdate();

    }




    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        PushResult pushMessage;
        pushMessage= (PushResult) getIntent().getSerializableExtra("pushmessage");
        if (pushMessage!=null){
            switch (pushMessage.getCode()){
                case 1:
                    tabViews.get(userType==2?2:0).setSelected(true);
                    viewPager.setCurrentItem(userType==2?2:0, false);
                    break;
            }
        }else {
            pageNo = getIntent().getIntExtra("pageNo", 0);
            tabViews.get(pageNo).setSelected(true);
            viewPager.setCurrentItem(pageNo, false);
        }

    }

    @OnClick({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab1:
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.tab2:
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.tab3:
                if (userType == 2) {
                    viewPager.setCurrentItem(2, false);
                }
                break;
            case R.id.tab4:
                viewPager.setCurrentItem(userType == 2 ? 3 : 2, false);
                break;
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void checkAppPermission() {
        PackageManager pkgManager = getPackageManager();
        //读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(WRITE_EXTERNAL_STORAGE, getPackageName()) == PERMISSION_GRANTED;

        //read phone state用于获取 imei 设备信息
        boolean phoneStatePermission =
                pkgManager.checkPermission(READ_PHONE_STATE, getPackageName()) == PERMISSION_GRANTED;

        //获取位置权限
        boolean locationWifiPermission = pkgManager.checkPermission(ACCESS_COARSE_LOCATION, getPackageName()) == PERMISSION_GRANTED;
        boolean locationGPSPermission = pkgManager.checkPermission(ACCESS_FINE_LOCATION, getPackageName()) == PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneStatePermission || !locationWifiPermission || !locationGPSPermission) {
            ActivityCompat.requestPermissions(this, new String[]{
                    WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
            }, 0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
            // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
            PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), PushIntentService.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
        if (member != null) {
            BaseApp.getInstance().setMember(member);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
                    PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
                    // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
                    PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), PushIntentService.class);
                } else {
                    //checkMMS();
                    show();
                }
                return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //权限申请失败则跳转至设置
    private void show() {
        final UIAlertView view = new UIAlertView(mContext, "温馨提示", "权限已被关闭，是否需要重新设置", "取消", "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        view.show();
    }

    private void checkUpdate(){
        Call<ResultDO<Version>> call = MemberClient.getApiAdapter().checkVersion(2, DeviceUtils.getVersionCode(getApplicationContext()));
        call.enqueue(new Callback<ResultDO<Version>>() {
            @Override
            public void onResponse(Call<ResultDO<Version>> call, Response<ResultDO<Version>> response) {
                ResultDO<Version> resultDO = response.body();
                if (isFinish){return;}
                if (resultDO != null && resultDO.getCode() == 0) {
                    final Version version = resultDO.getResult();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                            intent.putExtra("version",version);
                            startActivity(intent);
                        }
                    },2000);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Version>> call, Throwable t) {

            }
        });
    }

    public void setPage(int p){
        viewPager.setCurrentItem(p,false);
    }
}
